using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;

public partial class app_frame : System.Web.UI.MasterPage
{
    public security hdds;
    public string message;

    protected void Page_PreInit(object sender, EventArgs e)
    {
        //this.ContentPlaceHolder2.th = Session["Theme"].ToString();
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        // For Header 03-Sep-2007        
        //manageCollapsiblePanel();
        manageADs();
        manageEmbedCodes();
        setLogo();
        showFeedBackOption();
        setPageTitle();
        this.hdds = new security(Session["userid"].ToString());
        if (!IsPostBack)
        {

            if (!Request.RawUrl.Contains("displayhelp.aspx"))
                mn_main = this.hdds.load_menu(mn_main);
            else
            {
                LinkButton1.Visible = false;
                LinkButton2.Visible = false;
                LinkButton3.Visible = false;

                //LinkButton3.Text = "<img alt='Close' src='images/" + Session["Theme"].ToString().ToLower().Replace("theme","") + "/logout.jpg' style='border:0'/>";

                //LinkButton3.OnClientClick = "javascript:window.close()";
            }

            mn_main.MaximumDynamicDisplayLevels = 10;
        }

        if (lbl_user_name != null)
        {
            lbl_user_name.Text = Session["user_name"].ToString();// +(Session["user_role"] == null ? "" : ("<br><b>Role</b>:&nbsp;" + Session["user_role"].ToString()));
            if (!IsPostBack)
            {
                security se = new security();
                mn_recentvisit = se.loadLastAccessedMenu(mn_recentvisit);
                //mn_quick_links = se.loadQuickLinks(mn_quick_links);
                //if (HttpContext.Current.Session["roleid"] != null)
                //    if (HttpContext.Current.Session["roleid"].ToString() == "377e55cec8d53d7d" || HttpContext.Current.Session["roleid"].ToString() == "e7029dafbe379f85")
                if (Session["roleid"] != null)
                    if (Session["roleid"].ToString() != "")
                        quicklink.Text = se.loadQuickLinks().ToString();
                if (quicklink.Text.Trim() == "") ql.Visible = false;
            }
        }
        if (Request.QueryString["pgs_id"] != null)
        {
            string strPagesetRowID = Request.QueryString["pgs_id"].ToString();
        }
        if (Request.QueryString["mn"] != null) //added by Prithi on 21-Aug-2008
        {
            string strfinal = "";
            load_menuname(Request.QueryString["mn"].ToString(), ref strfinal);

            ltaccordian.Text = strfinal;

        }
    }
    private void showFeedBackOption()
    {
        feedbackdivtrigger.Visible = false;
        div_feedback.Visible = false;
        //return;
        if (IsPostBack) return;        
        try
        {
            HDDatabase hdd = new HDDatabase();
            DataTable dt = hdd.GetDataTable("select * from sy_acr_mem where af_row_id='3e7357b3af6b74e1'");
            hdd = null;
            if (dt != null)
            {
                if (dt.Rows.Count > 0)
                {
                    if (dt.Rows[0]["mem_value1"].ToString() == "true" || dt.Rows[0]["mem_value1"].ToString() == "1")
                    {
                        feedbackdivtrigger.Visible = true;
                        div_feedback.Visible = true;
                        div_feedback.Style.Add("display", "none");//to avoid flickering
                    }
                    else
                    {
                        feedbackdivtrigger.Visible = false;
                        div_feedback.Visible = false;
                    }
                }
            }
            
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in showFeedBackOption. " + e.Message);
        }
    }
    private void setPageTitle()
    {
        try
        {
            if (Session["pageTitle"] != null)
            {
                Page.Header.Title = Session["pageTitle"].ToString();
            }
            else
            {
                if (System.IO.File.Exists(HttpContext.Current.Server.MapPath(".") + "\\maxbloxtitle.ini"))
                {
                    System.IO.StreamReader sr = new System.IO.StreamReader(HttpContext.Current.Server.MapPath(".") + "\\maxbloxtitle.ini");
                    Session["pageTitle"] = sr.ReadLine();
                    Page.Header.Title = Session["pageTitle"].ToString();
                    sr.Close();
                    sr = null;
                }
            }
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in setPageTitle function. Error: " + e.Message);
        }
    }
    private void manageADs()
    {
        //return;
        //lblAD.Text="&nbsp;";
        try
        {
            HDDatabase hddAD = new HDDatabase(Session["servercon"].ToString());
            string str = "";
            //for (int i = 0; i < Session.Keys.Count; i++)
            //    str = Session.Keys[i].ToString();
            DataTable dt = hddAD.GetDataTable("select * from ngcompany where company_id='" + Session["company_id"].ToString() + "'");
            dt = hddAD.GetDataTable("select * from AD_Manager where company_id='" + dt.Rows[0]["af_row_id"].ToString() + "' and show_ads=1 order by sequence");
            if (dt == null)
            {
                hddAD = null;
                //lblAD.Text = "&nbsp;";
                return;
            }
            if (dt.Rows.Count > 0)
            {
                string[] locations = new string[] { "tdcAD1", "tdcAD2" };
                setAD(dt, locations);
                //if (dt.Rows[0]["show_ads"].ToString().ToLower() == "true")
                //{


                //DynamicDisplayI ddi = new DynamicDisplayI();
                //for (int j = 0; j < locations.Length; j++)
                //{
                //    HtmlTableCell htc = (HtmlTableCell)ddi.FindControl(this.Controls, locations[j]);
                //    htc.Controls.Add(new LiteralControl(dt.Rows[j]["ad_code"].ToString()));
                //}
                //ddi = null;
                //lblAD.Text = dt.Rows[0]["ad_code"].ToString();
                //}
            }
            else
            {
                hddAD = null;
                //lblAD.Text = "&nbsp;";
                return;
            }
            //hddAD = null;
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in manageADs function. Error: " + e.Message);
            //lblAD.Text = "&nbsp;";
        }
    }
    private void manageEmbedCodes()
    {
        try
        {
            HDDatabase hddEmbed = new HDDatabase(Session["servercon"].ToString());
            string str = "";
            //for (int i = 0; i < Session.Keys.Count; i++)
            //    str = Session.Keys[i].ToString();
            DataTable dt = hddEmbed.GetDataTable("select * from sy_embed_codes");
            if (dt == null)
            {
                hddEmbed = null;
                return;
            }
            if (dt.Rows.Count > 0)
            {
                setEmbedCode(dt);
            }
            else
            {
                hddEmbed = null;
                return;
            }
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in manageEmbedCodes function. Error: " + e.Message);
        }
    }
    private void setEmbedCode(DataTable dtEmbedCode)
    {
        if (dtEmbedCode == null) return;
        if (!dtEmbedCode.Columns.Contains("code")) return;
        if (dtEmbedCode.Rows.Count < 1) return;
        DynamicDisplayI ddi = new DynamicDisplayI();
        string content = "";
        try
        {
            foreach (DataRow dr in dtEmbedCode.Rows)
            {
                content += dr["code"].ToString();
            }
            embed_code_literal.Text = content;
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in setEmbedCode function. Error: " + e.Message);
        }
        finally
        {
            ddi = null;
        }
    }
    private void setAD(DataTable dtAd, string[] locations)
    {
        if (dtAd == null) return;
        if (dtAd.Rows.Count < 1) return;
        DynamicDisplayI ddi = new DynamicDisplayI();
        try
        {
            for (int j = 0; j < locations.Length; j++)
            {
                DataRow[] drs = dtAd.Select("sequence=" + Convert.ToString(j + 1));
                if (drs.Length > 0)
                {
                    HtmlTableCell htc = (HtmlTableCell)ddi.FindControl(this.Controls, locations[j]);
                    htc.Controls.Add(new LiteralControl(drs[0]["ad_code"].ToString()));
                }
            }
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in setAD function. Error: " + e.Message);
        }
        finally
        {
            ddi = null;
        }
    }
    private void manageCollapsiblePanel()
    {
        if (Session["collapsed"] != null)
        {
            CollapsiblePanelExtender1.Collapsed = Convert.ToBoolean(Session["collapsed"].ToString());
            //Panel1.Enabled = !Convert.ToBoolean(Session["collapsed"].ToString());
        }
    }
    protected void LinkButton1_Click(object sender, EventArgs e)
    {
        Response.Redirect("PagesetWizard.aspx");
    }
    protected void menulink_Click(object sender, EventArgs e)
    {
        Response.Redirect("MenuPage.aspx");
    }
    protected void lb_logout_Click(object sender, EventArgs e)
    {
        string sRedirect = "";
        hdds = new security();
        if (hdds.allRightsForNGMODEL())
            sRedirect = "Logout.aspx?LG=index.aspx";
        else
            sRedirect = "Logout.aspx?LG=" + ConfigurationManager.AppSettings["LoginPage"]; //default.aspx";
        // Modified by 'Imran Gani' 13-Mar-2013, to get login page from web config
        LogWriter.WriteLog("Session End : " + DateTime.Now.ToString());
        //hdds.updateUserTheme();
        AuditLog AL = new AuditLog();
        AL.updateUserInCompany();
        AL = null;
        if (!Page.User.Identity.IsAuthenticated)
        {
            if (Page.Request.Cookies["ASP.NET_SessionId"] != null)
            {
                Response.Cookies["ASP.NET_SessionId"].Expires = DateTime.Now.AddYears(-30);
            }
            Session.Abandon();
        }

        if (sRedirect != "")
            Response.Redirect(sRedirect);
        else
            Response.Redirect("Logout.aspx");
    }

    protected void mnu_theme_MenuItemClick(object sender, MenuEventArgs e)
    {
        if (e.Item.Text != "")
        {
            Session["Theme"] = e.Item.Value + "Theme"; //Session["Theme"] = e.Item.Text + "Theme"; //change by Jeya Prabha on 17-Sep-2007
            Response.Redirect(HttpContext.Current.Request.Url.ToString());
        }
    }

    protected void lb_help_Click(object sender, EventArgs e)
    {

    }
    protected void lb_home_Click(object sender, EventArgs e)
    {
        Navigator ng = new Navigator();
        string retrn = ng.getUserHomePage();
        ng = null;
        Response.Redirect(retrn);
    }
    public void load_menuname(string strMenuRowId, ref string strfinal) //added by Prithi on 21-Aug-2008 to load navigation menu 
    {
        try
        {
            //string strtext;
            DataRow drmenu = hdds.hddb.GetTableRow("select menu_name,parent_menu_id from sy_mnu where af_row_id = '" + strMenuRowId.Replace("'", "''") + "';");
            if (drmenu != null)
            {
                string strmenuname = CommonFunctions.SafeEncode(drmenu["menu_name"].ToString());
                string strparent1 = drmenu["parent_menu_id"].ToString();

                if (strparent1 != "")
                {

                    load_menuname(strparent1, ref strfinal);
                    string rtnavigate = navigate(strMenuRowId);
                    if (rtnavigate != "")
                    {
                        strfinal = strfinal + "&nbsp;<b>>></b>&nbsp;" + "<a href='" + rtnavigate + "' >" + strmenuname + "</a>";
                        return;
                    }
                    else
                    {
                        strfinal = strfinal + "&nbsp;<b>>></b>&nbsp;" + rtnavigate + strmenuname;
                        return;
                    }
                }
                else
                {
                    string rtnavigate = navigate(strMenuRowId);

                    if (rtnavigate != "")
                    {
                        strfinal = strfinal + "<a href='" + rtnavigate + "' >" + strmenuname + "</a>";
                        return;
                    }
                    else
                    {
                        strfinal = strfinal + rtnavigate + strmenuname;
                        return;
                    }
                }
                drmenu = null;

            }
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in load_menuname function. Error: " + e.Message);
        }


    }

    public string navigate(string strMenuRowId)//added by Prithi on 21-Aug-2008 to generate the url for navigation menu
    {
        string strMenuNavigateUrl = "";
        try
        {
            DataRow drurl = hdds.hddb.GetTableRow("select pageset_url_type,pageset_id,menu_click,pageset_url from sy_mnu where af_row_id = '" + strMenuRowId.Replace("'", "''") + "';");
            if (drurl != null)
            {
                string strPagesetUrlType = drurl["pageset_url_type"].ToString();
                string strmenuclick = drurl["menu_click"].ToString();
                string strPagesetRowID = drurl["pageset_id"].ToString();
                string strPagesetUrl = "";
                if (strPagesetRowID != "")
                {
                    string strPagesetUrlParam = "?mn=" + strMenuRowId.ToString() + "&pgs_id=" + strPagesetRowID;

                    if (strmenuclick == "2" && strPagesetUrlType == "2")
                    {
                        strPagesetUrl = drurl["pageset_url"].ToString();
                        strMenuNavigateUrl = strPagesetUrl + strPagesetUrlParam;
                    }



                    else if (strPagesetUrlType == "3") // for external link there is no parameters 
                    {
                        if (!strPagesetUrl.StartsWith("http", StringComparison.OrdinalIgnoreCase))
                        {
                            strPagesetUrl = "http://" + strPagesetUrl;
                        }
                        strMenuNavigateUrl = strPagesetUrl;

                    }
                    else
                    {
                        strPagesetUrl = "DisplayGrid.aspx";
                        strMenuNavigateUrl = strPagesetUrl + strPagesetUrlParam;
                    }



                }


            }
            return strMenuNavigateUrl;
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in navigate function. Error: " + e.Message);
            return strMenuNavigateUrl;
        }

    }
    private void setLogo()
    {
        security s = null;
        try
        {
            if (IsPostBack) return;//logic for transparent and large images
            s = new security();
            s.setLogo(ref ltrl_logo);
        }
        catch(Exception ex)
        {
            LogWriter.WriteLog("Error : SetLogo : "+ ex.Message);
        }
        finally
        {
            s = null;
        }
    }

    ////private void setLogo()
    ////{
    ////    if (IsPostBack) return;//logic for transparent and large images
    ////    ltrl_logo.Text = "<div class='backs'></div>";
    ////    string temp = "url('images/LightBlue/logo.gif');";
    ////    DynamicDisplayI ddi = new DynamicDisplayI();
    ////    HDDatabase hddLogo = null;
    ////    security s = null;
    ////    try
    ////    {
    ////        if (Session["company_afrowid"] != null)
    ////        {
    ////            DirectoryInfo di = new DirectoryInfo(Server.MapPath(".") + "\\Images\\CustomLogo");
    ////            FileInfo[] fis = di.GetFiles(Session["company_afrowid"].ToString() + "*");
    ////            if (fis.Length > 0)
    ////            {
    ////                temp = "url('images/CustomLogo/" + fis[0].Name + "')";
    ////                //ltrl_logo.Text = "<img src='Images/CustomLogo/" + fis[0].Name + "' />";
    ////                ltrl_logo.Text = "<table border='0' cellpadding='0' cellspacing='0' width='236' height='76'><tr><td align=\"center\" valign=\"middle\" style=background:url('images/CustomLogo/" + fis[0].Name + "');background-repeat:no-repeat;></td></tr></table>";
    ////            }
    ////            else//if another user in the same company logs out
    ////            {
    ////                if (Session["hasCustomLogo"] != null)
    ////                {
    ////                    string fName = ""; string ext = "";
    ////                    s = new security();
    ////                    s.createCustomLogo(ref fName, ref ext);
    ////                    ltrl_logo.Text = "<table border='0' cellpadding='0' cellspacing='0' width='236' height='76'><tr><td align=\"center\" valign=\"middle\" style=background:url('images/CustomLogo/" + Session["company_afrowid"] + ext + "');background-repeat:no-repeat;></td></tr></table>";
    ////                }
    ////            }
    ////        }
    ////        //HtmlTableCell htc = (HtmlTableCell)ddi.FindControl(this.Controls, "td_logo");
    ////        //htc.Style.Add("background",temp);
    ////    }
    ////    catch (Exception e)
    ////    {

    ////    }
    ////    finally
    ////    {
    ////        hddLogo = null;
    ////        ddi = null;
    ////        s = null;
    ////    }
    ////}
}
